//
//  JLRJViewController.m
//  Estate
//
//  Created by heyong on 16/5/26.
//  Copyright © 2016年 ttsx. All rights reserved.
//
#define DIC_EXPANDED @"expanded" //是否是展开 0收缩 1展开
#define DIC_ARARRY @"array"
#define DIC_TITILESTRING @"title"
//#define CELL_HEIGHT 46.*BIZ

#import "DiaryModel.h"
#import "JLAddRJViewController.h"
#import "RJTableCell.h"

#import "JLRJViewController.h"
#import "TTZhuanJianRightView.h"

@interface JLRJViewController ()<UITableViewDelegate, UITableViewDataSource>
//侧边栏/
@property (strong ,nonatomic)TTZhuanJianRightView *rightView;
//所有监理员
@property (nonatomic,copy) NSMutableArray *jianliArr;
//选中监理员
@property (nonatomic,copy) NSMutableArray *jianliArrSelect;
@property (nonatomic,assign) BOOL isz;
//添加按钮
@property (strong, nonatomic)UIButton *addBtn;

@property (strong, nonatomic)NSMutableArray *dataArray;

//表格
@property(strong, nonatomic)UITableView *tableView;

@end


@implementation JLRJViewController

// 数据源
- (NSMutableArray *)dataArray {
    if(_dataArray==nil){
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}

// 表格
- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-44-49-50*BIZ)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        [_tableView registerNib:[UINib nibWithNibName:@"RJTableCell" bundle:nil] forCellReuseIdentifier:@"RJCell"];
        _tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
        _tableView.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    [self.view addSubview:self.tableView];

    // 添加
    self.addBtn = [[UIButton alloc]initWithFrame:CGRECTS(260, 360, 100, 100)];
    [self.addBtn addTarget:self action:@selector(clickAddBtn) forControlEvents:UIControlEventTouchUpInside];
    [_addBtn setImage:[UIImage imageNamed:@"add_2"] forState:UIControlStateNormal];
    [self.view addSubview:_addBtn];
    
    // 添加通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"Refresh_jl_rj" object:nil];
    NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
    // 专业监理员
    if ([role isEqualToString:@"USER_07"]) {
        self.jianliArr = [LSUtility queryByType:@"USER_03"];
        self.jianliArrSelect = self.jianliArr;
        self.isz = YES;
        [self addShaixuanBtn];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIWindow *myWindow=[UIApplication sharedApplication].keyWindow;
            [myWindow addSubview:self.listView];
        });
    }
    // 查找数据
    [self initDataSource];
}
-(NSString *)getUserIDWithArray:(NSMutableArray *)arr{
    if (self.isz) {
        NSString *str = [NSString stringWithFormat:@"\'%@\'",USERID];
        for (NSDictionary *dic in arr) {
            NSString *userid = dic[@"userid"];
            str=[str stringByAppendingString:[NSString stringWithFormat:@",\'%@\'",userid]];
        }
        return str;
        
    }else{
        NSString *str = @"";
        for (NSDictionary *dic in arr) {
            NSString *userid = dic[@"userid"];
            if ([str isEqualToString:@""]) {
                str = [NSString stringWithFormat:@"\'%@\'",userid];
            }else{
                str=[str stringByAppendingString:[NSString stringWithFormat:@",\'%@\'",userid]];
            }
        }
        return str;
    }
    
}
//懒加载
-(TTZhuanJianRightView *)listView{
    if(_rightView==nil){
        _rightView=[[TTZhuanJianRightView alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH,0,DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT) dataArr:self.jianliArr];
        WEAKSELF
        _rightView.clickOkBtnBlock = ^(NSMutableArray *seleceArr) {
            if (seleceArr.count>0) {
                weakSelf.jianliArrSelect = seleceArr;
                weakSelf.isz = NO;
            }else{
                weakSelf.jianliArrSelect = weakSelf.jianliArr;
                weakSelf.isz = YES;
            }
            [weakSelf refresh:nil];
        };
    }
    return _rightView;
}
-(void)addShaixuanBtn{
    //弹出选择人物视图
    UIButton *rightBtn=[[UIButton alloc]initWithFrame:CGRECTS(DEF_SCREEN_WIDTH-70, 30, 70, 30)];
    rightBtn.tag=101;
    rightBtn.backgroundColor=[UIColor colorWithRed:0.78 green:0.26 blue:0.09 alpha:1.00];
    [rightBtn setTitle:@"人员选择" forState:UIControlStateNormal];
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:13.];
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightBtn];
}
#pragma mark-添加按钮
- (void)rightBtnClick:(UIButton *)sender{
    
    [UIView animateWithDuration:0.4 animations:^{
        _rightView.frame =CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_HEIGHT(self.view));
    }];
}

- (void)refresh:(id)sender{
    [self.dataArray removeAllObjects];
    [self initDataSource];
}

// 初始化数据
- (void)initDataSource {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSMutableDictionary *dic;
    FMResultSet *result;
    NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
    //专监
    if([role isEqualToString:@"USER_07"]){
        NSString *userids = [self getUserIDWithArray:self.jianliArrSelect];
        NSString *sql =  [NSString stringWithFormat:@"SELECT COUNT(*) as count ,substr(CREATE_TIME,1,7) AS condition,substr(CREATE_TIME,1,4) as year,substr(CREATE_TIME,6,2) as month FROM WORK_DIARY WHERE PRO_ID='%@'  AND DIARY_USER in(%@) and DIARY_TYPE='DIARY_02' GROUP BY substr(CREATE_TIME,1,7)  ORDER BY date(CREATE_TIME) desc",PROID,userids];
        result = [db executeQuery:sql];
    }else{
        result=[db executeQuery:SQL_WORKREDDIARY_SELECT(PROID, USERID)];
    }
    
    while ([result next]) {
        //查询到 年
        NSString* year= [result stringForColumn:@"year"];
        //查询到月
        NSString *month =[LSUtility deletaeZero:[result stringForColumn:@"month"]] ;
        //展开页查询条件
        NSString *condition=[result stringForColumn:@"condition"];
        NSString *sqlStr = @"";
        // 根据日期查询展开的数据
        NSString *role = DEF_PERSISTENT_GET_OBJECT(@"role");
        //专监
        if([role isEqualToString:@"USER_07"]){
            NSString *userids = [self getUserIDWithArray:self.jianliArrSelect];
            sqlStr =  [NSString stringWithFormat:@"select *,substr(DIARY_TIME,1,10) AS Day from WORK_DIARY WHERE PRO_ID = '%@'  AND DIARY_USER in(%@) and DIARY_TYPE='DIARY_02' AND substr(DIARY_TIME,1,7)='%@'  ORDER BY DIARY_TIME desc", PROID, userids, condition];
        }else{
            sqlStr = [NSString stringWithFormat:@"select *,substr(DIARY_TIME,1,10) AS Day from WORK_DIARY WHERE PRO_ID = '%@'  AND DIARY_USER ='%@' and DIARY_TYPE='DIARY_02' AND substr(DIARY_TIME,1,7)='%@'  ORDER BY DIARY_TIME desc", PROID, USERID, condition];
        }
        
        
        // 查询到记录
        NSMutableArray *DetailArr=[NSMutableArray array];
        FMResultSet *results=[db executeQuery:sqlStr];
        while ([results next]) {
            DiaryModel *model=[[DiaryModel alloc]init];
            model.diaryId=[results stringForColumn:@"ID"];
            model.PRO_ID=[results stringForColumn:@"PRO_ID"];
            model.DIARY_USER= [LSUtility getuserIdByUserName:
                               [results stringForColumn:@"DIARY_USER"]][@"REAL_NAME"];
            model.DIARY_TYPE=[results stringForColumn:@"DIARY_TYPE"];
            model.DIARY_DESC=[results stringForColumn:@"DIARY_DESC"];
            model.CREATE_TIME=[results stringForColumn:@"CREATE_TIME"];
            model.DIARY_TIME=[results stringForColumn:@"DIARY_TIME"];
            model.day=[results stringForColumn:@"Day"];
            model.TOUR_INFO=[results stringForColumn:@"TOUR_INFO"];
            model.EXTEND_INFO=[results stringForColumn:@"EXTEND_INFO"];
            model.CHECK_INFO=[results stringForColumn:@"CHECK_INFO"];
            model.WEATHER=[results stringForColumn:@"WEATHER"];
            model.SITE_INFO=[results stringForColumn:@"SITE_INFO"];
            model.SUPERVISE_INFO=[results stringForColumn:@"SUPERVISE_INFO"];
            model.FOLLOW_INFO=[results stringForColumn:@"FOLLOW_INFO"];
            model.SAFE_INFO=[results stringForColumn:@"SAFE_INFO"];
            model.OTHER_INFO=[results stringForColumn:@"OTHER_INFO"];
            //迭代新增类型 日记引入
            model.JIANCHA_INFO=[results stringForColumn:@"JIANCHA_INFO"];
            model.ZHILIANG_INFO=[results stringForColumn:@"ZHILIANG_INFO"];
            model.JINDU_INFO=[results stringForColumn:@"JINDU_INFO"];
            model.CAILIAO_INFO=[results stringForColumn:@"CAILIAO_INFO"];
            model.YINBI_INFO=[results stringForColumn:@"YINBI_INFO"];
            model.SHOUFAWEN_INFO=[results stringForColumn:@"SHOUFAWEN_INFO"];
            model.JIANZHENG_INFO=[results stringForColumn:@"JIANZHENG_INFO"];
            model.SHOUFAWEN_INFO=[results stringForColumn:@"SHOUFAWEN_INFO"];
            model.ENTER_EXTER_COMM_INFO=[results stringForColumn:@"ENTER_EXTER_COMM_INFO"];
            model.MEETING_INFO=[results stringForColumn:@"MEETING_INFO"];
            model.REVIEW_INFO=[results stringForColumn:@"REVIEW_INFO"];
            model.REVIEW_SCORE=[results stringForColumn:@"REVIEW_SCORE"];
            model.REVIEW_USER=[results stringForColumn:@"REVIEW_USER"];
            model.REVIEW_STATE=[results stringForColumn:@"REVIEW_STATE"];
            model.FILEIDS=[results stringForColumn:@"FILEIDS"];
            model.STATE=[results stringForColumn:@"STATE"];
            model.CREATE_USER_NAME=[results stringForColumn:@"CREATE_USER_NAME"];
            model.PATROL_RECORD_INFO = [results stringForColumn:@"PATROL_RECORD_INFO"];
            model.SAFE_RECORD_INFO = [results stringForColumn:@"SAFE_RECORD_INFO"];
            model.CREATE_IP=[results stringForColumn:@"CREATE_IP"];
            model.LOCAL_MODIFY_STATE=[results stringForColumn:@"LOCAL_MODIFY_STATE"];
            [DetailArr addObject:model];
        }
        //查询到数量
        NSString *count=[result stringForColumn:@"count"];
        //拼接成标题
        NSString *tiemAndCount=[NSString stringWithFormat:@"%@年%@月(%@条)",year,month,count];
        //标题添加到数组
        //        [array addObject:tiemAndCount];
        //创建一个字典 包含数组，分组名，是否展开的标示
        dic=[[NSMutableDictionary alloc] initWithObjectsAndKeys:DetailArr,DIC_ARARRY,tiemAndCount,DIC_TITILESTRING,[NSNumber numberWithInt:0],DIC_EXPANDED,nil];
        //将字典加入数组
        [self.dataArray addObject:dic];
    }
    [db close];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic = [_dataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
        
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section = indexPath.section;
    long row = indexPath.row;
    
    //得到改组下信息
    NSMutableDictionary *dic = [self.dataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    DiaryModel *model = array[row];
    
    RJTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"RJCell" forIndexPath:indexPath];
    // 状态or类型
    cell.type=model.REVIEW_STATE;
    // 标题
    cell.title.text=[NSString stringWithFormat:@"%@日记",model.day];
    // 时间
    cell.time.text=model.CREATE_TIME;//DIARY_TIME 跟安卓保持一致


    // 记录人
    cell.name.text=model.DIARY_USER ;
    return cell;
}

// 设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH, CELL_HEIGHT-10)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    //设置分组标题
    [eButton setTitle:[[self.dataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:16.*BIZ];
    
    //设置button的图片和标题的相对位置
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0,5, 0,0)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(0,DEF_SCREEN_WIDTH-30, 0,0)];
    
    //添加btn
    [hView addSubview: eButton];
    return hView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 10;
    }else{
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70*BIZ;
}

//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46*BIZ;
}

#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dic=[self.dataArray objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    DiaryModel *model=array[indexPath.row];
    JLAddRJViewController *jlAdd=[[JLAddRJViewController alloc]init];
    //判断日记是否未同步 是否未审核

    BOOL dataSyn= [self queryDiaryDataSynCheck];
    
    if(dataSyn){
        //判断是否是当天能否编辑
        jlAdd.isEdit=[LSUtility isSameDayDiary:model.CREATE_TIME andTyepe:model.REVIEW_STATE];
    }else{
        jlAdd.isEdit=NO;
    }
    
    jlAdd.flag=@"look";
    if(![model.REVIEW_STATE isEqualToString:@"0"]){
        //已经被审阅，包含评分
        jlAdd.identity=@"";
    }
    jlAdd.model=model;
    [self.navigationController pushViewController:jlAdd animated:YES];
}

#pragma mark - 添加日记
- (void)clickAddBtn {
    if ([LSUtility isExistAndType]) {
        
        //判断日记是否同步 是否审核
        BOOL dataSyn = [self queryDiaryDataSyn];
        //已经同步
        if (dataSyn) {
            
        } else {
            JLAddRJViewController *jlAdd=[[JLAddRJViewController alloc]init];
            jlAdd.flag=@"add";
            jlAdd.isEdit=YES;
            [self.navigationController pushViewController:jlAdd animated:YES];
        }
    } else {
        JLAddRJViewController *jlAdd=[[JLAddRJViewController alloc]init];
        jlAdd.flag=@"add";
        jlAdd.isEdit=YES;
        [self.navigationController pushViewController:jlAdd animated:YES];
    }
}

//判断日记是否同步
- (BOOL)queryDiaryDataSyn {
    NSString *sql=[NSString stringWithFormat:@"SELECT id,date(DIARY_TIME),date(CREATE_TIME) ,LOCAL_MODIFY_STATE,review_state FROM WORK_DIARY WHERE  date(DIARY_TIME) = '%@' AND DIARY_USER='%@'",[LSUtility dateNow],USERID];
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    BOOL dataSyn = NO;
    FMResultSet *result = [db executeQuery:sql];
    while ([result next]) {
        NSString *state=[result stringForColumn:@"review_state"];
        NSString *LOCAL_MODIFY_STATE=[result stringForColumn:@"LOCAL_MODIFY_STATE"];
        
        if ([state isEqualToString:@"1"]) {
            [LSUtility showToastWithMessage:@"该日记已经审核，不可更改！" inView:self.navigationController.view Andtime:2];
            dataSyn=YES;
            
        }else if(![LOCAL_MODIFY_STATE isEqualToString:@"ADD"]&&![LOCAL_MODIFY_STATE isEqualToString:@"MOD"]){
            [LSUtility showToastWithMessage:@"该日记已经同步到服务器端，不可更改！" inView:self.navigationController.view Andtime:2];
            dataSyn=YES;
        }
        break;
    }
    [db close];
    return dataSyn;
}

// 判断日记是否未同步 是否未审核
- (BOOL)queryDiaryDataSynCheck {
    NSString *sql = [NSString stringWithFormat:@"SELECT id,date(DIARY_TIME),date(CREATE_TIME) ,LOCAL_MODIFY_STATE,review_state FROM WORK_DIARY WHERE  date(DIARY_TIME) = '%@' AND DIARY_USER='%@'",[LSUtility dateNow],USERID];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    BOOL dataSyn=NO;
    BOOL check=NO;
    FMResultSet *result=[db executeQuery:sql];
    while ([result next]) {
        NSString *state=[result stringForColumn:@"review_state"];
        NSString *LOCAL_MODIFY_STATE=[result stringForColumn:@"LOCAL_MODIFY_STATE"];
        
        if ([state isEqualToString:@"0"]) {
            check=YES;
        }
        if([LOCAL_MODIFY_STATE isEqualToString:@"ADD"]||[LOCAL_MODIFY_STATE isEqualToString:@"MOD"]){
            dataSyn=YES;
        }
        break;
    }
    [db close];
    if (dataSyn&&check) {
        return YES;
        
    } else {
        return NO;
    }
}

#pragma mark -- 内部调用
// 对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
- (void)collapseOrExpand:(long)section {
    NSMutableDictionary *dic = [_dataArray objectAtIndex:section];
    int expanded = [[dic objectForKey:DIC_EXPANDED] intValue];
    
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
        
    } else {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
}

// 返回指定节是否是展开的
-(int)isExpanded:(long)section{
    NSDictionary *dic=[_dataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

// 按钮被点击时触发
-(void)expandButtonClicked:(id)sender{
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}


@end

